/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package proyectoempresa.DAO;


import Utildao.Utildao;
import java.util.List;
import javax.persistence.EntityManager;

/**
 *
 * @author Diego
 */
public abstract class ComunDao_1<T> {
    private T instancia;
    private EntityManager entitimanager;

    public ComunDao_1(T instancia) {
        this.instancia = instancia;
        entitimanager=Utildao.getEntityManager();
    }

    public EntityManager getEntitimanager() {
        return entitimanager;
    }

    public void setEntitimanager(EntityManager entitimanager) {
        this.entitimanager = entitimanager;
    }

    public T getInstancia() {
        return instancia;
    }

    public void setInstancia(T instancia) {
        this.instancia = instancia;
    }

    public void persistence() throws Exception{
    entitimanager.getTransaction().begin();
        try {
            this.entitimanager.persist(instancia);
            this.entitimanager.getTransaction().commit();
        } catch (Exception e) {
            if (entitimanager.getTransaction().isActive()) {
                entitimanager.getTransaction().rollback();
                    throw e;
            }
        }
    }

    public void update() throws Exception{
        this.entitimanager.getTransaction().begin();
        try{
            this.entitimanager.merge(instancia);
            this.entitimanager.getTransaction().commit();
        }catch(Exception e){
            if (this.entitimanager.getTransaction().isActive())
                // Arreglar el Error y reintentar
                this.entitimanager.getTransaction().rollback();
            throw e;
        }
    }

    public void remover() throws Exception{
    entitimanager.getTransaction().begin();
        try {
            this.entitimanager.remove(instancia);
             this.entitimanager.getTransaction().commit();
        } catch (Exception e) {
            if (entitimanager.getTransaction().isActive()) {
                entitimanager.getTransaction().rollback();
                throw e;
            }
        }
    }

  public T findById(Long id){
     return (T) entitimanager.find(instancia.getClass(), id);
  }

  public abstract List<T> buscarTodos();




}
